<template>
  <a-modal v-model:visible="visible" :title="title" @ok="handleOk" width="1500px" @cancel="onCancel" :maskClosable="false" :keyboard="false" :ok-button-props="{ disabled: controlDisabled }">
    <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" :rules="rules" ref="proclamationForm" :model="form">
      <a-form-item v-show="false" has-feedback name="id">
        <a-input v-model:value="form.id" :disabled="controlDisabled" />
      </a-form-item>
      <a-form-item label="公告标题" has-feedback name="title">
        <a-input v-model:value="form.title" :disabled="controlDisabled" />
      </a-form-item>
      <a-form-item label="发布范围" has-feedback name="issueScopeArr">
        <a-select v-model:value="form.issueScopeArr" mode="multiple" :disabled="controlDisabled">
          <a-select-option mode="multiple" :value="item.value" v-for="(item, index) in issueScopeOptions" :key="index">{{
            item.label }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-row style="justify-content: space-between;!important">
        <a-form-item style="width: 20%;" label="有效期" name="effectiveDays" has-feedback :label-col="{ span: 10 }">
          <a-input-number v-model:value="form.effectiveDays" style="width: 100%" :min="0" string-mode
            :disabled="controlDisabled" />
        </a-form-item>
        <a-form-item class="form-item-inline" label="状态" has-feedback name="status" :label-col="{ span: 5 }">
          <a-select v-model:value="form.status" style="width: 200px" :disabled="controlDisabled">
            <a-select-option value="0">草稿</a-select-option>
            <a-select-option value="1">发布</a-select-option>
            <a-select-option value="2">归档</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="form-item-inline" label="发布人" name="issuerName" :label-col="{ span: 6 }">
          <a-input disabled v-model:value="form.issuerName" style="width: 200px" />
        </a-form-item>
        <a-form-item class="form-item-inline" label="发布单位" name="issueDepartName" :label-col="{ span: 7 }">
          <a-input disabled v-model:value="form.issueDepartName" style="width: 200px" />
        </a-form-item>
        <a-form-item class="form-item-inline" label="发布时间" name="issueTime" :label-col="{ span: 7 }">
          <a-input disabled v-model:value="form.issueTime" />
        </a-form-item>
      </a-row>
      <a-form-item label="公告内容" has-feedback name="content">
        <!-- 编辑器 -->
        <WangEditor v-if="visible" :disabled="controlDisabled" ref="wangEditor" v-model:content="form.content">
        </WangEditor>
      </a-form-item>
      <a-form-item label="附件">
        <a-upload name="file" :disabled="controlDisabled" :file-list="fileList" :before-upload="beforeUpload"
          @remove="handleRemove" @preview="downloadAttachment">
          <a-button :disabled="controlDisabled"> <upload-outlined />点击上传</a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { useUserStore } from '@/store/modules/user';
import { getDeptList } from '@/api/system/dept/index';
import { deleteAttament, downloadAttament } from '@/api/workorder/common/attachment';
import { save, modify, getByIdWithAttachment } from '@/api/workorder/rcbg/proclamation';
import { toRaw } from '@vue/reactivity';
import { uploadAttament } from '@/views/workorder/common/common';
import type { Rule } from 'ant-design-vue/es/form';
import type { UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import WangEditor from '@/components/editor/WangEditor.vue';
import { ref, reactive, onMounted, computed } from 'vue';
const userStore = useUserStore();
export default {
  name: 'ProclamationModal',
  components: { WangEditor, UploadOutlined },
  setup(props, context) {
    let controlDisabled = ref(false);
    const wangEditor = ref(null);
    const proclamationForm: any = ref(null);
    const userInfo: any = computed(() => userStore.userInfo);
    let removeFile: any = [];
    // 控制弹窗显示
    let visible = ref(false);
    // 弹框标题
    let title = ref('新增公告');
    // 文件列表
    const fileList: any = ref<UploadProps['fileList']>([]);
    // form表单
    let form = reactive({
      id: '',
      title: '',
      content: '',
      effectiveDays: '',
      issueScope: '',
      issueScopeArr: [],
      issuer: '',
      issuerName: '',
      issueDepart: '',
      issueDepartName: '',
      status: '',
      issueTime: '',
    });
    // 发布范围选择
    let issueScopeOptions: Array<{ label: string, value: string }> = reactive([]);

    /**
     * 内容校验
     * @param _rule 
     * @param value 
     */
    const validatorContent = async (_rule: Rule, value: string) => {
      const text = value.replace(/<[^>]+>/g, '').trim();
      if (text === '') {
        return Promise.reject('请输入公告内容');
      } else {
        return Promise.resolve();
      }
    };

    /**
     * 表单校验规则
     */
    const rules: Record<string, Rule[]> = {
      title: [{ required: true, trigger: 'blur' }],
      issueScopeArr: [{ required: true, trigger: 'blur' }],
      effectiveDays: [{ required: true, trigger: 'blur' }],
      status: [{ required: true, trigger: 'blur' }],
      content: [{ required: true, validator: validatorContent, trigger: 'blur' }],
    };


    onMounted(() => {
      loadDeptList();
    });

    /**
     * 初始化方法
     */
    function init(param?: any) {
      controlDisabled.value = param && param.disabled;
      if (param && param.id) {
        // 修改
        title.value = controlDisabled.value ? '查看公告' : '修改公告';
        loadProclamationDetail(param.id);
      } else {
        title.value = '新增公告';
        form.issuerName = userInfo.value.user.loginName;
        form.issuer = userInfo.value.user.id;
        form.issueDepartName = userInfo.value.user.org.name;
        form.issueDepart = userInfo.value.user.org.id;
      }
      visible.value = true;
    }

    /**
     * 加载部门
     */
    async function loadDeptList() {
      const res = await getDeptList();
      const deptOptions = res.map((dept) => {
        return {
          label: dept.name,
          value: dept.id,
        };
      });
      issueScopeOptions.push(...deptOptions);
    }
    /**
     * 加载公告详情
     * @param id 
     */
    async function loadProclamationDetail(id: string) {
      const info = await getByIdWithAttachment(id);
      if (info) {
        form.id = info.id;
        form.title = info.title;
        form.content = info.content;
        form.effectiveDays = info.effectiveDays;
        form.issueScope = info.issueScope;
        form.issueScopeArr = info.issueScope.split(",");
        form.issuer = info.issuer;
        form.issuerName = info.issuerName;
        form.issueDepart = info.issueDepart;
        form.issueDepartName = info.issueDepartName;
        form.status = info.status;
        form.issueTime = info.issueTime;
        if (info.attachmentList && info.attachmentList.length > 0) {
          let list = info.attachmentList.map(file => {
            return {
              id: file.id,
              uid: file.uid,
              name: file.fileName,
              status: 'done',
              url: file.path,
            }
          });
          fileList.value.splice(0, fileList.value.length);
          fileList.value.push(...list);
        }
      }
    }

    /**
     * 点击确定
     */
    function handleOk() {
      // 表单校验
      proclamationForm.value.validate().then(async () => {
        // 验证通过
        form.issueScope = form.issueScopeArr.join(',');
        let res;
        if (form.id) {
          // 修改
          res = await modify(toRaw(form))
        } else {
          // 新增
          res = await save(toRaw(form));
        }
        if (res && res.code == 200) {
          // 上传附件
          if (form.id) {
            await uploadAttament(fileList.value.filter(file => !file.id), 'proclamation', res.data.id);
          } else {
            await uploadAttament(fileList.value, 'proclamation', res.data.id);
          }
          // 删除移除的附件
          if (removeFile.length > 0) {
            await deleteAttament(removeFile.map(file => file.id));
          }
          message.success(form.id ? '修改成功' : '新增成功');
          visible.value = false;
          onCancel();
        } else {
          message.error(res.message ? res.message : form.id ? '修改失败' : '新增失败');
        }
      })
    }

    const handleRemove = file => {
      if (file.id) {
        // 移除的是已上传的文件
        removeFile.push(file);
      }
      const index = fileList.value.indexOf(file);
      const newFileList = fileList.value.slice();
      newFileList.splice(index, 1);
      fileList.value = newFileList;
    };

    const beforeUpload: UploadProps['beforeUpload'] = file => {
      fileList.value = [...fileList.value, file];
      return false;
    };

    /**
     * 下载文件
     * @param file 
     */
    const downloadAttachment = file => {
      if (file.id) {
        // 存在id，是已上传的文件 
        downloadAttament(file.id);
      }
    }

    const onCancel = () => {
      // 重置表单和校验状态
      proclamationForm.value.resetFields();
      // 清空附件
      fileList.value.splice(0, fileList.value.length);
      removeFile = [];
      context.emit("onCancel");
    };

    return {
      visible,
      title,
      fileList,
      form,
      issueScopeOptions,
      wangEditor,
      proclamationForm,
      controlDisabled,
      rules,
      init,
      handleOk,
      loadDeptList,
      handleRemove,
      beforeUpload,
      onCancel,
      loadProclamationDetail,
      downloadAttachment
    };
  },
};
</script>